Fork me on GitHub

iOS WKWebView https 加载不受信任的站点

原因

公司要对接一个第三方平台,然后就有了一个可奇葩的逻辑,用户填写完相关信息后,点击提交,然后服务器返回一个网页的源代码……需要用WebView加载这个网页。

实现的时候发现,我自己写的简单的网页源码可以加载,但是服务器返回的就是无法加载。后来把源码保存成文件以后,用浏览器打开发现,该网页链接的站点是一个不受信任的站点,应该是因为服务器证书无效而不受信任。

解决办法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
self.wkWeb.navigationDelegate = self

// 实现以下代理方法
func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let cred = URLCredential.init(trust: challenge.protectionSpace.serverTrust!)
completionHandler(.useCredential, cred)
}

// 如果是OC
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
NSURLCredential * card = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential,card);
}
}

其他

有朋友说还需要在 plist 文件中设置:

Allow Arbitrary Loads in Web Content 置为 YES,或者将Allow Arbitrary Loads置位YES

但是我实际测试以后发现,不设置也可以打开,可能是具体情况不同的原因吧!

-------------本文结束感谢您的阅读-------------

本文作者:乔羽 / FightingJoey

发布时间:2018年03月07日 - 15:17

最后更新:2018年09月27日 - 10:09

原始链接:https://fightingjoey.github.io/2018/03/07/开发/iOS WKWebView https 加载不受信任的站点/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

坚持原创技术分享,您的支持将鼓励我继续创作!